﻿#include "ctrlObjects.h"
#include "MdiFDWindow.h"
#include "formDev.h"

#include <QCheckBox>
#include <QMenu>
#include <QStack>
#include <QDebug>

ctrlObjects::ctrlObjects(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);

	// TreeWidget 自动列宽
	ui.treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);

	//允许使用右键菜单
	ui.treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
	//允许多选
	ui.treeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);

	//关联QTreeWidget控件的点击事件
	connect(ui.treeWidget, &QTreeWidget::itemClicked, this, &ctrlObjects::HandleTreeWidgetItemClicked);
	//关联右键菜单事件
	connect(ui.treeWidget, &QTreeWidget::customContextMenuRequested, this, &ctrlObjects::ShowContextMenu);
	//关联搜索框事件
	connect(ui.lineEdit, &QLineEdit::textChanged, this, &ctrlObjects::onTextChanged);  //变化
	connect(ui.lineEdit, &QLineEdit::returnPressed, this, &ctrlObjects::onTextChanged);//回车

}

ctrlObjects::~ctrlObjects()
{
}

//处理隐藏复选框的点击事件
void ctrlObjects::OnHiddenCheckBoxClicked()
{
	QCheckBox* pCheck = (QCheckBox*)sender();
	formDev* pForm = (formDev*)pCheck->property("formDev").toULongLong();
	pForm->setVisibleDev(!pCheck->isChecked());
}

//处理树形控件点击事件
void ctrlObjects::HandleTreeWidgetItemClicked(QTreeWidgetItem* item, int column)
{
	//获取存放在Item中的指针
	formDev* node = (formDev*)item->data(0, Qt::UserRole).toULongLong();
	//将所有选择状态清空
	node->root()->resetStateMaching();
	node->setSelected(true);
	//更新一下属性框数据
	emit node->sigActiveControlObject(node, 2);
}

//处理右键打开菜单选项
void ctrlObjects::ShowContextMenu(const QPoint& pos)
{
	//获取右键点击的Item
	QTreeWidgetItem* item = ui.treeWidget->itemAt(pos);
	if (!item) return;

	QMenu contextMenu;
	QAction* action1 = contextMenu.addAction(QTCN("隐藏"));
	QAction* action2 = contextMenu.addAction(QTCN("取消隐藏"));
	
	//获取用户选择
	QPoint qmenu_point = mapToGlobal(pos);
	qmenu_point.setY(qmenu_point.y() + contextMenu.sizeHint().height());
	QAction* selectedAction = contextMenu.exec(qmenu_point);

	if (selectedAction == action1) 
	{
		//隐藏
		Set_NodeHiddenState(true);
	}
	else if (selectedAction == action2)
	{
		//不隐藏
		Set_NodeHiddenState(false);
	}
}

//处理搜索按钮点击事件
void ctrlObjects::onTextChanged()
{
	QString searchmes = ui.lineEdit->text();
	int result_num = 0;
	//恢复折叠
	ui.treeWidget->collapseAll();
	//遍历所有Item比对
	for (QTreeWidgetItem* item : allItems) 
	{
		if (!item) continue;

		// 设置背景色
		item->setBackground(0, QBrush(QColor(255, 255, 255))); // 恢复设置为白色
		QString columnValue = item->text(0);  // 获取第一列的文本
		QString tooltip = item->toolTip(0);

		if (searchmes.isEmpty()) 
		{
			continue;  
		}
		else if (columnValue.contains(searchmes) || tooltip.contains(searchmes))
		{
			// 设置背景色 
			item->setBackground(0, QBrush(QColor(0, 255, 0))); // 设置为绿色
			//逐级展开各个节点直到根节点
			while (item)
			{
				item = item->parent();
				if (item)
				{
					item->setExpanded(true);
				}
			}
			//改变检索结果计数
			result_num++;
		}
	}

	//改变检索结果计数
	ui.label_result->setText(QTCN("检索结果:") + QString::number(result_num) + QTCN("个"));
}

//添加子节点到控件树
void ctrlObjects::Add_ChildNode(formDev* node, QTreeWidgetItem* pItem)
{	
	//将当前控件添加到节点中
	pItem->setData(0, Qt::UserRole, QVariant((qulonglong)node));
	pItem->setText(0, node->getObjectName());
	pItem->setText(2, node->getClassName());

	//构建Item的tooltip
	QString tooltip = "";
	if (node->propertyValue("text") != "")
		tooltip.append(node->propertyValue("text"));
	if (node->propertyValue("title") != "")
		tooltip.append((tooltip != "" ? "\n" : "") + node->propertyValue("title"));
	if (node->propertyValue("windowTitle") != "")
		tooltip.append((tooltip != "" ? "\n" : "") + node->propertyValue("windowTitle"));

	if(tooltip!="") 
		pItem->setToolTip(0, tooltip);

	//添加复选框
	QCheckBox* pCheck = new QCheckBox();
	pCheck->setProperty("item", QVariant((qulonglong)pItem));
	pCheck->setProperty("formDev", QVariant((qulonglong)node));
	pCheck->setChecked(!node->isVisibleDev());
	connect(pCheck, &QCheckBox::clicked, this, &ctrlObjects::OnHiddenCheckBoxClicked);
	ui.treeWidget->setItemWidget(pItem, 1, pCheck);

	//递归处理子节点
	QList<formDev*> subObjects = node->getSubObjects();
	for (auto& a : subObjects)
	{
		QTreeWidgetItem* childnode = new QTreeWidgetItem();
		pItem->addChild(childnode);

		//添加子节点到控件树
		Add_ChildNode(a, childnode);
	}
}


//根据formDev对象查找Item
QTreeWidgetItem* ctrlObjects::findTreeItem(formDev* pForm)
{
	QStack<QTreeWidgetItem*> stack;

	int count = ui.treeWidget->topLevelItemCount();
	for (int i = 0; i < count; i++)
	{
		QTreeWidgetItem* tmpItem1 = ui.treeWidget->topLevelItem(i);

		stack.push(tmpItem1);
		while (stack.count() > 0)
		{
			QTreeWidgetItem* tmpItem2 = stack.pop();
			formDev* pObject = (formDev*)tmpItem2->data(0, Qt::UserRole).toULongLong();
			if (pObject == pForm) return tmpItem2;

			for (int j = 0; j < tmpItem2->childCount(); j++)
			{
				QTreeWidgetItem* tmpItem3 = tmpItem2->child(j);
				stack.push(tmpItem3);
			}
		}
	}
	return NULL;
}

//删除某一节点
void ctrlObjects::removeChildNode(formDev* pForm)
{
	QTreeWidgetItem* pItem1 = findTreeItem(pForm);
	if (pItem1) delete pItem1;
}


//选择当前节点，并展开父节点
void ctrlObjects::ExpanedParent(QTreeWidgetItem* pItem)
{
	//QStack<QTreeWidgetItem*> stack;

	//int count = ui.treeWidget->topLevelItemCount();
	//for (int i = 0; i < count; i++)
	//{
	//	QTreeWidgetItem* tmpItem1 = ui.treeWidget->topLevelItem(i);

	//	stack.push(tmpItem1);
	//	while (stack.count() > 0)
	//	{
	//		QTreeWidgetItem* tmpItem2 = stack.pop();
	//		
	//		tmpItem2->setSelected(false);

	//		for (int j = 0; j < tmpItem2->childCount(); j++)
	//		{
	//			QTreeWidgetItem* tmpItem3 = tmpItem2->child(j);
	//			stack.push(tmpItem3);
	//		}
	//	}
	//}

	ui.treeWidget->clearSelection();
	QTreeWidgetItem* tmpItem = pItem;

	while (tmpItem)
	{
		tmpItem = tmpItem->parent();
		if (tmpItem)
		{
			tmpItem->setExpanded(true);
		}
	}

	ui.treeWidget->scrollToItem(pItem);

	pItem->setSelected(true);
}

//添加根节点到控件树
void ctrlObjects::Add_RootNode(formDev* pForm, int flag)
{
	if (flag == 0)
	{
		//UI上的树形控件
		QTreeWidget* treewidget = ui.treeWidget;
		clearAllNodes();

		//MDI下的子控件作为树的根节点
		QList<formDev*> subObjects = pForm->getSubObjects();
		for (auto& a : subObjects)
		{
			QTreeWidgetItem* rootnode = new QTreeWidgetItem();
			treewidget->addTopLevelItem(rootnode);
			Add_ChildNode(a, rootnode);
		}
	}
	else
	{
		QTreeWidgetItem* pItem1 = findTreeItem(pForm);
		QTreeWidgetItem* pItem2 = findTreeItem(pForm->getParent());
		
		qDebug() << pItem1 << pItem2;

		if (pItem2 == NULL)
		{
			if (pItem1 == NULL)
			{
				QTreeWidgetItem* pNewItem = new QTreeWidgetItem();
				ui.treeWidget->addTopLevelItem(pNewItem);
				Add_ChildNode(pForm, pNewItem);
				ExpanedParent(pNewItem);
			}
			else
			{
				ExpanedParent(pItem1);
			}
		}
		else
		{
			if (pItem1 == NULL)
			{
				QTreeWidgetItem* pNewItem = new QTreeWidgetItem();
				pItem2->addChild(pNewItem);
				Add_ChildNode(pForm, pNewItem);
				ExpanedParent(pNewItem);
			}
			else
			{
				ExpanedParent(pItem1);
			}
		}
	}

	//获取新的全部Item列表
	QTreeWidgetItemIterator it(ui.treeWidget);
	allItems.clear();
	while (*it)
	{
		allItems.append(*it);
		++it;
	}

	//刷新时清空搜索栏
	ui.lineEdit->setText("");
}

//清空所有节点
void ctrlObjects::clearAllNodes()
{
	ui.treeWidget->clear();
}

//设置节点的隐藏状态：true == 隐藏；false == 不隐藏；
void ctrlObjects::Set_NodeHiddenState(const bool& flag)
{
	QList<QTreeWidgetItem*> choiceitemlist = ui.treeWidget->selectedItems();
	for (auto& a : choiceitemlist)
	{
		//获取存放在Item中的指针
		formDev* pForm = (formDev*)a->data(0, Qt::UserRole).toULongLong();
		pForm->setVisibleDev(!flag);
		//获取隐藏复选框
		QWidget* widget = ui.treeWidget->itemWidget(a, 1);
		QCheckBox* checkBox = qobject_cast<QCheckBox*>(widget);
		checkBox->setChecked(flag);
	}
}